﻿@model  WebApp.Models.Department
@{
	ViewBag.Title = "部门信息";
}
<!-- MAIN CONTENT -->
<div id="content">
    <!-- quick navigation bar -->
    <div class="row">
        <div class="col-xs-12 col-sm-7 col-md-7 col-lg-4">
            <h1 class="page-title txt-color-blueDark">
                <i class="fa fa-table fa-fw "></i>
                组织架构
                <span>
                    >
                  部门信息
                </span>
            </h1>
        </div>
        <div class="col-xs-12 col-sm-5 col-md-5 col-lg-8">
            
        </div>
    </div>
    <!-- end quick navigation bar -->
    <!-- widget grid -->
    <section id="widget-grid" class="">
        <!-- row -->
        <div class="row">
            <!-- NEW WIDGET START -->
            <article class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
                <!-- Widget ID (each widget will need unique ID)-->
                <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false" data-widget-deletebutton="false">
                    <!-- widget options:
                    usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false">
                    data-widget-colorbutton="false"
                    data-widget-editbutton="false"
                    data-widget-togglebutton="false"
                    data-widget-deletebutton="false"
                    data-widget-fullscreenbutton="false"
                    data-widget-custombutton="false"
                    data-widget-collapsed="true"
                    data-widget-sortable="false"
                    -->
                    <header>
                        <span class="widget-icon"> <i class="fa fa-table"></i> </span>
                        <h2>部门信息</h2>
                    </header>

                     <!-- widget div-->
                    <div>
                        <!-- widget edit box -->
                        <div class="jarviswidget-editbox">
                            <!-- This area used as dropdown edit box -->
                        </div>
                        <!-- end widget edit box -->
                        <!-- widget content -->
                        <div class="widget-body no-padding">
                          <div class="sk-spinner sk-spinner-wave">
                            <div class="sk-rect1"></div>
                            <div class="sk-rect2"></div>
                            <div class="sk-rect3"></div>
                            <div class="sk-rect4"></div>
                            <div class="sk-rect5"></div>
                          </div>
                            <div class="widget-body-toolbar">
                                <div class="row">
                                    <div class="col-sm-8  ">
                                        <!-- 开启授权控制请参考 @@if (Html.IsAuthorize("Create") -->
                                        <div class="btn-group btn-group-sm">
                                            <button onclick="append()" class="btn btn-default"> <i class="fa fa-plus"></i> 新增 </button>
                                        </div>
                                        <div class="btn-group btn-group-sm">
                                            <button onclick="removeit()" class="btn btn-default"> <i class="fa fa-trash-o"></i> 删除 </button>
                                        </div>
                                        <div class="btn-group btn-group-sm">
                                            <button onclick="accept()" class="btn btn-default"> <i class="fa fa-floppy-o"></i> 保存 </button>
                                        </div>
                                        <div class="btn-group btn-group-sm">
                                            <button onclick="reload()" class="btn btn-default"> <i class="fa fa-refresh"></i> 刷新 </button>
                                        </div>
                                        <div class="btn-group btn-group-sm">
                                            <button onclick="reject()" class="btn btn-default"> <i class="fa fa-ban"></i> 取消 </button>
                                        </div>
                                        <div class="btn-group btn-group-sm">
                                            <button type="button" onclick="importexcel()" class="btn btn-default"><i class="fa fa-cloud-upload"></i> 导入数据 </button>
                                            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                                <span class="caret"></span>
                                                <span class="sr-only">Toggle Dropdown</span>
                                            </button>
                                            <ul class="dropdown-menu">
                                                <li><a href="javascript:importexcel()"><i class="fa fa-file-excel-o"></i>  上传Excel </a></li>
                                                <li role="separator" class="divider"></li>
                                                <li><a href="javascript:downloadtemplate()"><i class="fa fa-download"></i> 下载模板 </a></li>
                                            </ul>
                                        </div>
                                        <div class="btn-group btn-group-sm">
                                            <button onclick="exportexcel()" class="btn btn-default"> <i class="fa fa-file-excel-o"></i> 导出Excel </button>
                                        </div>
                                        <div class="btn-group btn-group-sm">
                                            <button onclick="print()" class="btn btn-default"> <i class="fa fa-print"></i> 打印 </button>
                                        </div>
                                        <div class="btn-group btn-group-sm">
                                            <button onclick="dohelp()" class="btn btn-default"> <i class="fa fa-question-circle-o"></i> 帮助 </button>
                                        </div>
                                    </div>
                                    <div class="col-sm-4 text-align-right">
                                        <div class="btn-group btn-group-sm">
                                            <button onclick="window.history.back()" class="btn btn-sm btn-success"> <i class="fa fa-chevron-left"></i> 返回 </button>
                                        </div>
                                    </div>
                                </div>

                            </div>
                            <div class="alert alert-warning no-margin fade in">
                                <button class="close" data-dismiss="alert">
                                    ×
                                </button>
                                <i class="fa-fw fa fa-info"></i>
                                注意事项:
                            </div>
	                        <!--begin datagrid-content -->
	                        <div class="table-responsive">
		                         <table id="departments_datagrid">  
		                         </table>
                    		</div>
		                    <!--end datagrid-content -->
                         </div>
                        <!-- end widget content -->
                    </div>
                    <!-- end widget div -->
                </div>
                <!-- end widget -->
            </article>
            <!-- WIDGET END -->
        </div>
        <!-- end row -->
    </section>
    <!-- end widget grid -->
	<!-- file upload partial view -->
	@Html.Partial("_ImportWindow",new ViewDataDictionary {{ "EntityName","Department" }})		 
	<!-- end file upload partial view -->
    <!-- detail popup window -->
    @Html.Partial("_PopupDetailFormView",new WebApp.Models.Department())
    <!-- end detail popup window -->
            
</div>
<!-- END MAIN CONTENT -->

@section Scripts {
<script type="text/javascript">
      //是否启用弹窗口模式新增编辑数据
      const POPUPMODE = false;
      //是否强制从后台取值
      const REQUIRBACKEND = false;
      //是否开启行内编辑
      const EDITINLINE = false;
      //上传导入参数设定
      const entityname = "Department";
      var department = {};
      
      //下载Excel导入模板
      function downloadtemplate() {
          //默认模板路径存放位置
          var url = "/FileUpload/Download?file=/ExcelTemplate/Department.xlsx";
          $.fileDownload(url)
           .done(() => {
                    //console.log('file download a success!');
                })
           .fail(() => {
               $.messager.alert("错误","没有下载到导入模板[Department.xlsx]文件!","error"); 
            });           
       }
       //打印
       function print() {
            $dg.datagrid('print', 'DataGrid');
       }
        //打开Excel上传窗口
	   function importexcel() {
		    $("#importwindow").window("open");
	   }
	   //执行导出下载Excel
	   function exportexcel() {
				var filterRules = JSON.stringify($dg.datagrid("options").filterRules);
				//console.log(filterRules);
				$.messager.progress({ title: "正在执行导出!" });
				var formData = new FormData();
				formData.append("filterRules", filterRules);
				formData.append("sort", "Id");
				formData.append("order", "asc");
				$.postDownload("/Departments/ExportExcel", formData).then(res => {
                    $.messager.progress("close");
                }).catch(err => {
                    //console.log(err);
                    $.messager.progress("close");
                    $.messager.alert("错误", err.statusText, "error");
                });

		}
        //显示帮助信息
        function dohelp() {
            $.bigBox({
                title: "帮助信息",
                content: "如有问题请联系系统管理员",
                color: "#3276B1",
                timeout: 5000,
                icon: "fa fa-question swing animated"
               
            });
        }
        var editIndex = undefined;
        //选中记录
       function onSelect(index, row) {
          department = row;
       }
       //重新加载数据
	   function reload() {
			if (endEditing()) {
			    $dg.datagrid("reload");
                //$dg.datagrid("uncheckAll");
                //$dg.datagrid("unselectAll");
		    }
	   }
      //关闭编辑状态
	  function endEditing() {
			if (editIndex === undefined) { 
                return true; 
            }
			if ($dg.datagrid("validateRow", editIndex)) {
				var ed = $dg.datagrid("getEditor", { index: editIndex, field: "CompanyId" });
				var companyname = $(ed.target).combobox("getText");
				var companyid = $(ed.target).combobox("getValue");
				$dg.datagrid("getRows")[editIndex]["CompanyName"] =  companyname;
				$dg.datagrid("getRows")[editIndex]["CompanyId"] = companyid;
				$dg.datagrid("endEdit", editIndex);
				editIndex = undefined;
                return true;
			} else {
				return false;
			}
		}
    //单击列开启编辑功能
	function onClickCell(index, field) {
        department = $dg.datagrid('getRows')[index];
	    var _operates = ["_operate1", "_operate2", "_operate3", "ck"];
		if (!EDITINLINE || $.inArray(field, _operates) >= 0) {
				return;
		}
		if (editIndex !== index) {
		    if (endEditing()) {
			    $dg.datagrid("selectRow", index)
				   .datagrid("beginEdit", index);
                hook = true;
                editIndex = index;
				var ed = $dg.datagrid("getEditor", { index: index, field: field });
				if (ed) {
						($(ed.target).data("textbox") ? $(ed.target).textbox("textbox") : $(ed.target)).focus();
				}
			} else {
				$dg.datagrid("selectRow", editIndex);
			}
		}
	}
    //新增记录
	function append() {
        if (POPUPMODE) {
            //弹出新增窗口
            showPopupCreateWindow();
        } else {
			if (endEditing()) {
				//对必填字段进行默认值初始化
				$dg.datagrid("insertRow", 
                              {   
                                  index: 0,
                                  row: {
                                   
                                  }
                              });
				editIndex = 0;
				$dg.datagrid("selectRow", editIndex)
					.datagrid("beginEdit", editIndex);
                hook = true;
			}
        }
	}
    //删除编辑的行
	function removeit() {
        if($dg.datagrid("getChecked").length > 0 ){
            deletechecked();
        } else {
		   if (editIndex !== undefined) { 
    			$dg.datagrid("cancelEdit", editIndex)
					.datagrid("deleteRow", editIndex);
			   editIndex = undefined;
               hook = true;
           }
        }
	}
    //删除选中的行
    function deletechecked() {
        var rows = $dg.datagrid("getChecked");
        if (rows.length > 0) {
            var id = rows.map(item => {
                   return item.Id;
                });
            $.messager.confirm("确认", "你确定要删除这些记录?", result => {
                if (result) {
                    $.post("/Departments/DeleteCheckedAsync", { id: id })
                         .done(response => {
                                if (response.success) {
                                    reload();
                                } else {
                                    $.messager.alert("错误", response.err,"error");
                                }
                          })
                          .fail((jqXHR, textStatus, errorThrown) => {
						         //console.log(errorThrown);
						         $.messager.alert("错误", "提交错误了!" + errorThrown,"error");
					      });
                    }
                });  
         } else {
                $.messager.alert("提示", "请先选择要删除的记录!","question");
         }
     }
    //提交保存后台数据库
	function accept() {
			if (endEditing()) {
				if ($dg.datagrid("getChanges").length) {
					var inserted = $dg.datagrid("getChanges", "inserted");
					var deleted = $dg.datagrid("getChanges", "deleted");
					var updated = $dg.datagrid("getChanges", "updated");
					var item = new Object();
					if (inserted.length) {
						item.inserted = inserted;
					}
					if (deleted.length) {
						item.deleted = deleted;
					}
					if (updated.length) {
						item.updated = updated;
					}
					//console.log(JSON.stringify(item));
					$.post("/Departments/SaveDataAsync", item)
                     .done(response => {
						   //console.log(response);
						   if (response.success) {
							   $.messager.alert("提示", "保存成功!","info");
							   $dg.datagrid("acceptChanges");
							   $dg.datagrid("reload");
                               hook = false;
						   } else {
                               $.messager.alert("错误", response.err ,"error");
                           }
					    })
                      .fail((jqXHR, textStatus, errorThrown) => {
						//console.log(errorThrown);
						$.messager.alert("异常",  errorThrown,"error");
					  });
				}
			}
	}
	function reject() {
	    $dg.datagrid("rejectChanges");
	    editIndex = undefined;
	}
	function getChanges() {
	    var rows = $dg.datagrid("getChanges");
		//console.log(rows.length + " rows are changed!");
	}
    //弹出明细信息
	function showDetailsWindow(id,row,index) {
        if (REQUIRBACKEND) {
			//console.log(index, row);
            $.get("/Departments/PopupEditAsync/" + id)
             .done(data => {
                //console.log(data);
                loadData(id,data);
              })
             .fail((jqXHR, textStatus, errorThrown) => {
						$.messager.alert("错误", "获取数据异常!" + errorThrown,"error");
		      });
        } else {
            loadData(id, JSON.parse(row));
        }
	}
    //弹出新建窗口
    function showPopupCreateWindow() {
        //获取初始化对象
        if (REQUIRBACKEND) {
            $.get("/Departments/PopupCreate")
                .done(data => {
                    loadData(-1,data);
                 })
                .fail((jqXHR, textStatus, errorThrown) => {
                    $.messager.alert("错误", "初始化对象异常!" + errorThrown, "error");
                });
        } else {
           var item = {
                     
                };
           loadData(-1, item);   
        }
    }
    //初始化定义datagrid
    var $dg = $("#departments_datagrid");
    $(() => {
		 //定义datagrid结构
         $dg.datagrid({
                        rownumbers:true,
				        checkOnSelect:true,
				        selectOnCheck:true,
				        idField:'Id',
				        sortName:'Id',
				        sortOrder:'desc',
				        remoteFilter: true,
				        singleSelect: true,
				        onSelect: onSelect,
				        url: '/Departments/GetDataAsync',
				        method: 'get',
				        onClickCell: onClickCell,
				        pagination: true,
                        striped:true,   
                        columns: [[
                         /*开启CheckBox选择功能*/
                         /*{ field: 'ck', checkbox: true },*/
                         { 
                            field: '_operate1',
                            title:'操作',
                            width: 60,
                            sortable: false,
                            resizable: true,
                            formatter: function showdetailsformatter(value, row, index) {
                                         if(row.Id > 0){
                                              return '<button onclick="showDetailsWindow(\'' + row.Id + '\',\'' + JSON.stringify(row).replace(/\"/g, '&quot;') + '\',' + index +')" class="btn btn-default btn-xs" title="查看明细" ><i class="fa fa-pencil-square-o"></i> </button>';
                                         } else {
                                              return '<button class="btn btn-default btn-xs" disabled title="查看明细"  ><i class="fa fa-pencil-square-o"></i> </button>';
                                         }
                                     }
                          },
		     /*{field:'Id',width:80 ,sortable:true,resizable:true }*/
			{
                 field:'Name', 
                 title:'<span class="required">@Html.DisplayNameFor(model => model.Name)</span>', 
                 width:260,
                 editor:{
                          type:'textbox',
                          options:{ prompt:'@Html.DisplayNameFor(model => model.Name)',required:true ,validType:'length[0,50]'  }  
                       },
                 sortable:true,
                 resizable:true 
			},
			{
                 field:'Manager', 
                 title:'@Html.DisplayNameFor(model => model.Manager)', 
                 width:140,
                 editor:{
                          type:'textbox',
                          options:{ prompt:'@Html.DisplayNameFor(model => model.Manager)',required:false ,validType:'length[0,20]'  }  
                       },
                 sortable:true,
                 resizable:true 
			},
			{
                field:'CompanyId',
                title:'<span class="required">@Html.DisplayNameFor(model => model.CompanyId)</span>',
                width:160, 
                sortable:true, 
                resizable:true,
                formatter:(value,row) => {
				        return row.CompanyName;
					},
			    editor:{
					    type:'combobox',
					    options:{
								prompt:'@Html.DisplayNameFor(model => model.CompanyId)' ,
                                mode: 'remote',
								valueField:'Id',
								textField:'Name',
								method:'get',
								url:'/Departments/GetCompaniesAsync',
								required:true
							}
						}
			},
                 ]]
           });

           $dg.datagrid("enableFilter",[
				{
					  field: "Id",
					  type: "numberbox",
					  op:['equal','notequal','less','lessorequal','greater','greaterorequal']
				  },
		   {
				 field: "CompanyId",
				 type:"combobox",
				 options:{
								valueField:"Id",
								textField:"Name",
								method:"get",
								url:"/Departments/GetCompaniesAsync",
								onChange: value => {
								if (value === "" || value === null) {
									$dg.datagrid("removeFilterRule", "CompanyId");
								} else {
									$dg.datagrid("addFilterRule", {
										field: "CompanyId",
										op: "equal",
										value: value
								});
							}
							$dg.datagrid("doFilter");
						}
					}
		   },
		   ]);
	 });
</script>
<!--begin popup detailview javascript block -->
<script type="text/javascript">
    //load data by key
    var departmentid = 0;
    function loadData(id,data) {
         $("#detailswindow").window("open");
         departmentid = id;
         $('#department_form').form('load', data);
             }
    var $editform = $('#department_form');
    // save item
    function saveitem() { 
        if ($editform.form('enableValidation').form('validate')) {
            var department = $editform.serializeJSON();
                        var url = '/Departments/EditAsync';
            //判断是新增或是修改方法
            if (department.Id <= 0 || department.Id === null || department.Id === '') {
                url = '/Departments/CreateAsync';
            }
            var token = $('input[name="__RequestVerificationToken"]', $editform).val();
            $.ajax({
                    type: "POST",
                    url: url,
                    data: {
                        __RequestVerificationToken: token,
                        department:department
                    },
                    dataType: 'json',
                    contentType: 'application/x-www-form-urlencoded; charset=utf-8'
                })
                .done(response => {
                    if (response.success) {
                        $dg.datagrid('reload');
                        $.messager.alert("提示", "保存成功！","info");
                        $('#detailswindow').window("close");
                    } else {
                        $.messager.alert("错误",   response.err, "error");
                    }
                    })
                .fail((jqXHR, textStatus, errorThrown) => {
                        $.messager.alert("异常",   errorThrown,"error");
                    });
        }
    }
    // close window
    function closewindow() {
        $('#detailswindow').window('close');
    }
    // print form
    function printitem() {
         console.log('print.....');
    }

 
</script>


<!--end popup detailview javascript block -->
<script src="~/Scripts/jquery.filerupload.min.js"></script>
}

 
